package com.mxw.wechatai.controller;

import com.mxw.wechatai.entity.UserInfo;
import com.mxw.wechatai.mapper.UserInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
public class UserController {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @GetMapping("/login")
    public String loginPage() {
        return "login";
    }

    @GetMapping("/register")
    public String registerPage() {
        return "register";
    }

    @PostMapping("/user/login")
    @ResponseBody
    public Map<String, Object> login(@RequestParam String username,
                                   @RequestParam String password,
                                   HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        // 查询用户信息
        UserInfo userInfo = userInfoMapper.selectOne(
            new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getUserName, username)
                .eq(UserInfo::getPassword, password)
        );

        if (userInfo != null) {
            // 登录成功
            session.setAttribute("userInfo", userInfo);
            result.put("success", true);
            result.put("message", "登录成功");
        } else {
            // 登录失败
            result.put("success", false);
            result.put("message", "用户名或密码错误");
        }
        
        return result;
    }

    @PostMapping("/user/register")
    @ResponseBody
    public Map<String, Object> register(@RequestParam String username,
                                      @RequestParam String password,
                                      @RequestParam String email) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查用户名是否已存在
        UserInfo existingUser = userInfoMapper.selectOne(
            new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getUserName, username)
        );
        
        if (existingUser != null) {
            result.put("success", false);
            result.put("message", "用户名已存在");
            return result;
        }

        // 检查邮箱是否已存在
        existingUser = userInfoMapper.selectOne(
            new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getEmail, email)
        );
        
        if (existingUser != null) {
            result.put("success", false);
            result.put("message", "邮箱已被注册");
            return result;
        }

        try {
            // 创建新用户
            UserInfo newUser = new UserInfo();
            newUser.setUserName(username);
            newUser.setPassword(password);
            newUser.setEmail(email);
            newUser.setCount(50L); // 设置默认次数为50次
            newUser.setCreateTime(new Date()); // 设置创建时间
            
            // 保存用户信息
            userInfoMapper.insert(newUser);
            
            result.put("success", true);
            result.put("message", "注册成功");
            result.put("redirectUrl", "/login");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "注册失败：" + e.getMessage());
        }
        
        return result;
    }

    @GetMapping("/user/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/login";
    }

    @GetMapping("/user/info")
    @ResponseBody
    public Map<String, Object> getUserInfo(HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        UserInfo userInfo = (UserInfo) session.getAttribute("userInfo");
        
        if (userInfo != null) {
            result.put("success", true);
            result.put("username", userInfo.getUserName());
            result.put("count", userInfo.getCount());
            result.put("hasAuthCode", userInfo.getAuthCode() != null && !userInfo.getAuthCode().isEmpty());
        } else {
            result.put("success", false);
        }
        
        return result;
    }

    @PostMapping("/user/settings")
    @ResponseBody
    public Map<String, Object> saveSettings(@RequestParam String appid,
                                          @RequestParam String secret,
                                          HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        // 获取当前登录用户
        UserInfo userInfo = (UserInfo) session.getAttribute("userInfo");
        if (userInfo == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return result;
        }

        try {
            // 更新用户设置
            userInfo.setAppid(appid);
            userInfo.setSecret(secret);
            userInfoMapper.updateById(userInfo);
            
            // 更新session中的用户信息
            session.setAttribute("userInfo", userInfo);
            
            result.put("success", true);
            result.put("message", "设置保存成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "设置保存失败：" + e.getMessage());
        }
        
        return result;
    }

    @GetMapping("/user/settings")
    @ResponseBody
    public Map<String, Object> getSettings(HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        // 获取当前登录用户
        UserInfo userInfo = (UserInfo) session.getAttribute("userInfo");
        if (userInfo == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return result;
        }

        result.put("success", true);
        result.put("appid", userInfo.getAppid());
        result.put("secret", userInfo.getSecret());
        
        return result;
    }
} 